<template>
  <div class="contract-container">
    <div class="contract-left">
      <el-calendar ref="calendar" v-model="currentDate">
        <template #header="{ date }">
          <div class="el-calendar__title">{{ date }}</div>
          <div class="el-calendar__button-group">
            <el-button-group>
              <el-button size="small" @click="selectDate('prev-month')">
                <Icon icon="ep:arrow-left" />
              </el-button>
              <el-button size="small" type="primary" @click="selectDate('today')"> 今日 </el-button>
              <el-button size="small" @click="selectDate('next-month')">
                <Icon icon="ep:arrow-right" />
              </el-button>
            </el-button-group>
          </div>
        </template>
        <template #date-cell="{ data }">
          <div class="calendar-cell">
            <span>{{ data.day.split('-')[2] }}</span>
            <div class="flex mt-4px gap-col-4px">
              <template v-for="(dot, index) in getShowDots(data.day)" :key="index">
                <span
                  class="calendar-dot"
                  :class="[dot.type]"
                  :style="{ backgroundColor: dot.color, width: dot.width }"
                ></span>
              </template>
            </div>
          </div>
        </template>
      </el-calendar>
      <div class="legend">
        <div class="legend-item">
          <span class="calendar-dot expired-contract"></span>
          <span>到期合同</span>
        </div>
        <div class="legend-item">
          <span class="calendar-dot remind-contract"></span>
          <span>提醒合同</span>
        </div>
      </div>
    </div>

    <div class="contract-right">
      <ContentWrap class="search-wrap">
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="合同名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入合同名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="合同分类" prop="typeId">
            <el-select
              v-model="queryParams.typeId"
              placeholder="请选择分类"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SCHOOL_CONTRACT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              class="!w-240px"
            />
          </el-form-item>

          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['school:contract:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <!-- <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['school:contract:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button> -->
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap class="table-wrap table-list !mb-0">
        <el-table
          v-loading="loading"
          :data="filteredList"
          :stripe="true"
          :show-overflow-tooltip="true"
          height="100%"
        >
          <!-- <el-table-column label="编号" align="center" prop="id" /> -->
          <el-table-column label="合同编号" align="center" prop="contractNo" />
          <el-table-column label="合同名称" align="center" prop="name" />
          <el-table-column label="分类" align="center" prop="typeId">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SCHOOL_CONTRACT_TYPE" :value="scope.row.typeId" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="合同文件" align="center" prop="fileUrls" /> -->
          <el-table-column
            label="合同文件"
            align="center"
            prop="fileUrls"
            :show-overflow-tooltip="false"
          >
            <template #default="scope">
              <FileListView :file-list="scope.row.fileUrls" />
            </template>
          </el-table-column>
          <el-table-column
            label="合同到期时间"
            align="center"
            prop="expiredTime"
            :formatter="dateFormatter2"
            width="180px"
          />
          <el-table-column label="合同关联用户" align="center" prop="userNames" />
          <el-table-column label="提前提醒天数" align="center" prop="notifyDays" />
          <el-table-column label="备注" align="center" prop="remark" />
          <!-- <el-table-column label="排序" align="center" prop="sort" /> -->
          <!-- <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column> -->
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center" fixed="right" width="160">
            <template #default="scope">
              <el-button
                v-if="0 == scope.row.status"
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['school:contract:update']"
              >
                处理
              </el-button>
              <el-button
                v-if="0 == scope.row.status"
                link
                type="success"
                @click="handleStore(scope.row.id, 1)"
                v-hasPermi="['school:contract:update']"
              >
                归档
              </el-button>
              <el-button
                v-if="1 == scope.row.status"
                link
                type="success"
                @click="handleStore(scope.row.id, 0)"
                v-hasPermi="['school:contract:update']"
              >
                还原
              </el-button>
              <el-button
                v-if="0 == scope.row.status"
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['school:contract:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <!-- 无数据状态 -->
            <el-empty description="暂无合同数据" />
          </template>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </div>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <ContractForm ref="formRef" @success="handleFormSuccess" />
</template>

<script setup lang="ts">
import type { CalendarDateType, CalendarInstance } from 'element-plus'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { ContractApi, ContractVO } from '@/api/school/contract'
import ContractForm from './ContractForm.vue'
import { formatDate } from '@/utils/formatTime'
import Pagination from '@/components/Pagination/index.vue'
import { isNumber } from '@/utils/is'

/** 合同管理 列表 */
defineOptions({ name: 'SchoolContractView' })

// 定义合同点类型
interface ContractDot {
  type: string
  color: string
  width: string
}
const { query } = useRoute()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const calendar = ref<CalendarInstance>() // 日历组件实例
const currentDate: any = ref(new Date()) // 当前选中的日期
const selectedDate = ref(formatDate(new Date(), 'YYYY-MM-DD')) // 选中的日期字符串
const monthData = ref<Record<string, any>>({}) // 月份数据，记录每天的合同状态
const oldMonth = ref('') // 上一次查询的月份

const loading = ref(true) // 列表的加载中
const list = ref<ContractVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  name: undefined,
  typeId: undefined,
  createTime: undefined,
  day: formatDate(new Date(), 'YYYY-MM-DD'), // 添加day参数用于按日期查询
  pageNo: 1,
  pageSize: 10
})

//归档查询参数
const storeParams = reactive({
  id: 0,
  status: 0
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const filteredList = computed(() => {
  // 先根据搜索条件过滤
  let result = list.value
  // 根据主题搜索
  if (queryParams.name) {
    result = result.filter((item) => item.name.includes(queryParams.name!))
  }
  if (isNumber(queryParams.typeId)) {
    result = result.filter((item) => item.typeId === queryParams.typeId)
  }

  return result
})
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 如果有创建时间筛选，则使用分页接口
    if (queryParams.createTime) {
      const data = await ContractApi.getContractPage(queryParams)
      list.value = data.list
      total.value = data.total
    } else {
      // 使用getContractByDay获取当天合同列表
      const day = formatDate(new Date(queryParams.day), 'YYYYMMDD')
      const data = await ContractApi.getContractByDay(day)
      list.value = data || []
      total.value = 0
    }
  } finally {
    loading.value = false
  }
}

/** 获取指定月份的合同数据 */
const getMonthData = async (month: string) => {
  oldMonth.value = month
  try {
    // ContractApi.getContractByMonth返回示例数据:
    // [{
    //     "day": "20251001",
    //     "isHasExpired": false,
    //     "isHasRemind": false
    // }]
    const data = await ContractApi.getContractByMonth(month)
    monthData.value = {}
    // 处理返回的数据，按day作为key存储
    if (Array.isArray(data)) {
      data.forEach((item) => {
        monthData.value[item.day] = {
          isHasExpired: item.isHasExpired,
          isHasRemind: item.isHasRemind
        }
      })
    }
  } catch (error) {
    console.error('获取月份合同数据失败:', error)
  }
}

/** 获取指定日期的合同 */
const getDayContract = async (day: string) => {
  // 更新查询参数中的日期
  queryParams.day = day
  // 查询该日期的合同
  await getList()
}

/** 获取指定日期的状态点 */
const getShowDots = (day: string) => {
  const key = day.replace(/-/g, '')
  const contractData = monthData.value?.[key]
  const dots: ContractDot[] = []

  if (contractData) {
    // 到期合同 - 红色点
    if (contractData.isHasExpired) {
      dots.push({
        type: 'expired-contract',
        color: 'var(--el-color-danger)',
        width: '6px'
      })
    }

    // 提醒合同 - 绿色点
    if (contractData.isHasRemind) {
      dots.push({
        type: 'remind-contract',
        color: 'var(--el-color-success)',
        width: '6px'
      })
    }
  }

  return dots
}

/** 处理日期选择 */
const handleDaySelect = (value: Date) => {
  const dateStr = formatDate(value, 'YYYY-MM-DD')
  selectedDate.value = dateStr
  queryParams.createTime = undefined
  queryParams.typeId = undefined
  queryParams.name = undefined
  getDayContract(dateStr)
}

/** 处理日期点击 */
const handleDayClick = (data: any) => {
  const date = new Date(data.day)
  handleDaySelect(date)
}

/** 选择日期 */
const selectDate = (val: CalendarDateType) => {
  if (!calendar.value) return
  calendar.value.selectDate(val)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 归档按钮操作 */
const handleStore = async (id: number, status: number) => {
  try {
    // 二次确认
    const actionText = status === 1 ? '归档' : '还原'
    await message.confirm(`确定将此合同${actionText}吗？`)
    // 调用接口
    storeParams.id = id
    storeParams.status = status
    await ContractApi.storeContract(storeParams)
    message.success(t('common.success'))
    // 刷新列表
    await getList()
    // 重新获取当前月份数据以更新日历上的点
    const month = formatDate(currentDate.value, 'YYYYMM')
    await getMonthData(month)
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractApi.deleteContract(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    // 重新获取当前月份数据以更新日历上的点
    const month = formatDate(currentDate.value, 'YYYYMM')
    await getMonthData(month)
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContractApi.exportContract({
      name: queryParams.name,
      typeId: queryParams.typeId
    })
    download.excel(data, '合同管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 表单操作成功回调 */
const handleFormSuccess = async () => {
  // 重新获取当前月份数据以更新日历上的点
  const month = formatDate(currentDate.value, 'YYYYMM')
  await getMonthData(month)
  // 刷新列表
  await getList()
}

/** 监听日期变化 */
watch(currentDate, (val) => {
  const month = formatDate(val, 'YYYYMM')
  const day = formatDate(val, 'YYYY-MM-DD')

  // 如果月份变化了，重新获取月份数据
  if (oldMonth.value !== month) {
    getMonthData(month)
  }
  if (day) {
    handleDayClick({ day })
  }
  // 清空创建时间筛选
  if (queryParams.createTime) {
    queryParams.createTime = undefined
  }
})
watch(
  () => query.dayDate,
  (dayDate) => {
    const isUpdate = dayDate === currentDate.value
    if (dayDate) {
      currentDate.value = dayDate
    }
    if (isUpdate || !dayDate) {
      // 获取当前月份数据
      const month = formatDate(currentDate.value, 'YYYYMM')
      getMonthData(month)
      // 获取当前日期的会议预约
      handleDayClick({ day: currentDate.value })
    }
  },
  {
    immediate: true
  }
)
// onMounted(() => {
//   // 获取当前月份数据
//   const month = formatDate(currentDate.value, 'YYYYMM')
//   getMonthData(month)
//   // 获取当前日期的合同
//   handleDayClick({ day: currentDate.value })
// })
</script>

<style lang="scss" scoped>
.contract-container {
  display: flex;
  column-gap: 20px;
  height: $content-height;
}

.contract-left {
  width: 350px;
  padding: 15px;
  background-color: #fff;
  flex-shrink: 0;

  .legend {
    padding: 12px;
    margin-top: 12px;
    font-size: 14px;
    color: #606266;
    text-align: center;

    .legend-item {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      margin-right: 12px;

      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.contract-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .search-wrap,
  .table-wrap {
    background-color: #fff;
  }

  .table-list {
    // :deep() {
    //   .el-card__body {
    //     height: calc($content-height - 65px);
    //     overflow-y: hidden;
    //   }
    // }
  }
}

.calendar-cell {
  position: relative;
  display: flex;
  cursor: pointer;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.calendar-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  vertical-align: middle;
  border-radius: 100px;
}

.calendar-dot.expired-contract {
  background-color: var(--el-color-danger);
}

.calendar-dot.remind-contract {
  background-color: var(--el-color-success);
}

:deep() {
  .el-calendar__header {
    padding: 2px;
  }

  .el-calendar__body {
    padding: 0;
  }

  .el-calendar-day {
    height: 50px !important;
    text-align: center;
  }

  .el-calendar-table td.is-selected {
    background-color: var(--el-color-primary-light-9) !important;
  }
}
</style>
